// pages/msg_details/msg_details.js
var config = require('../../config.js')
var CryptoJS = require('./../../util/util.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    url:'http://apaicn.com/resources/',
    uuid:'',
    phone:'',
    info:[],
    showMsgpopup: false,
    unlockBtn: false,
    unlockShowDg: false,
    unlockValue: "",
    value:0,
    msg_timestamp:0,
    unlocktime:0,
    setInter: 0,
  },

  mqttPublish(key, data) {
    let _this = this
    return //test
    try{
      if ((!app.globalData.MQ || !app.globalData.MQ.connected)) {
      // app.AppGetDevList()
        app.initSocket()
          setTimeout(function () {
            console.log("mqttPublish 11111", app.globalData.MQ.connected);
            if (app.globalData.MQ.connected)
              app.globalData.MQ.publish(config.mqtt_baidu.unlock_top, data);
          }, 1000)
        return
      }
    // console.log("mqttPublish 222222");
      app.globalData.MQ.publish(config.mqtt_baidu.unlock_top, data);
    }
        catch(err) {
      console.log('publish fail', err)
      return
    }
  },
  sendUnlock(uuid, phone, lockpwd, unlocktimestamp, value)
  {
    // console.log('uuid',uuid,"phone",phone)
    // console.log('lockpwd', lockpwd, "unlocktimestamp", unlocktimestamp, "timevalue", value)
    var _this = this
    this.setData({
      unlockShowDg: false
    })

    var pwd = CryptoJS.Encrypt(lockpwd)
    wx.request({
      url: config.url.checkUnlockPwd,
      method: 'POST',
      dataType: "json",
      data: {
        uuid: uuid,
        phone: phone,
        password: pwd,
        timestamp: unlocktimestamp,
        value: value,
        client: config.client,
      },
      header: {
        // 'content-type': 'application/json', // 默认值
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success(res) {
        console.log(res.data)
        console.log("code:", res.data.code)
        console.log("data:", res.data.data)

        if (res.data.code == 200) {
         // var timestamp = new Date().getTime();
          var msg = { "code": "200", "uuid": uuid, "token": res.data.data, "timestamp": unlocktimestamp+"", "phone": phone}
          _this.mqttPublish(uuid, JSON.stringify(msg))
        }
        else {
          wx.showToast({
            title: '请输入正确的开锁密码',
            icon: 'none',
            duration: 2000
          })

        }

      },
      fail(e) {
        console.error(e)
     
      }
    })
  },


  onUnlockChange(e){
    // console.log(e)
    // console.log("onUnlockChange:", e.detail)
    var _this = this
    this.setData({
      unlockValue: e.detail
    })
    // console.log("unlockValue:", this.data.unlockValue)

    if(e.detail.length == 6)
    {
      var timestamp = parseInt(new Date().getTime() / 1000)
      _this.sendUnlock(_this.data.uuid, _this.data.phone, e.detail, timestamp, _this.data.value)
      // _this.sendUnlock(_this.data.uuid, _this.data.phone, e.detail, _this.data.unlocktimestamp, _this.data.value)
    }
  },

 

  onUnlockConfirm(e)
  {
    var _this = this 
    console.log("onUnlockConfirm")

    if(this.data.unlockValue == 6)
    {
      var timestamp = parseInt(new Date().getTime() / 1000)
      this.sendUnlock(_this.data.uuid, _this.data.phone, this.data.unlockValue, timestamp, _this.data.value)
      // this.sendUnlock(_this.data.uuid, _this.data.phone, this.data.unlockValue, _this.data.unlocktimestamp, _this.data.value)
    }
    else
    {
      wx.showToast({
        title: '请输入正确的开锁密码',
        icon: 'none',
        duration: 2000
      })
    }
  },

  onClose(){
    this.setData({
      unlockShowDg: false
    })
  },
  
  onConfirmBtn()
  {
    console.log("onConfirmBtn:" + this.data.unlockShowDg)
    this.setData({
      unlockShowDg: !this.data.unlockShowDg
    })
  },


  previewImage: function (e) {

    // console.log('url1', this.data.scene)
    //console.log('url2', this.data.scene.split(','))
    // wx.previewImage({
    //   urls: this.data.info.pic_url.split(',')
    //   // 需要预览的图片http链接  使用split把字符串转数组。不然会报错
    // })
  },


//dev_uuid: 11, msg_type: "远程开锁请求", pic_url: "20200429120816.jpg", msg_time: "2021-03-28 20:08:15", time: "2020-04-29",
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("cz options:" , options)
    var _this = this
    let uuid = options.uuid
    let data = JSON.parse(options.data)
    console.log("data:", data)

    // unlocktimestamp: e.currentTarget.dataset.value.fields.timestamp
    var msg_type = data.msg_type
    var hTime =  data.timestamp
    var qTime = parseInt(new Date().getTime() / 1000)

    console.log('hTime', hTime, 'qTime', qTime)
    console.log('msg_type', msg_type, 'index', options.index,'时间',qTime - hTime)
   
    if ((msg_type == 3) || (msg_type == '3')) 
    {
      if ((options.index == 0) || (options.index == '0')) 
      {
        if (qTime - hTime < 60) {
          var unlockt = hTime + 65 -qTime ;
         
          this.setData({
            unlockBtn: true,
            unlocktime: unlockt,
            msg_timestamp: hTime
          })

        }
      }
    }
   
    var phone = wx.getStorageSync('phone')
    if ((phone != "") && (phone != "")) {
      console.log('phone', phone)
    }
    else {
      wx.reLaunch({
        url: '../login/login?id=' + phone,
      })
    }
    // let dd = data.msg_time
    // console.log("msg_time:", data.msg_time)
    // str = dd.replace(/-/g, '/')
    // var date = new Date(str)
    // console.log("date:", date)
    // unlocktimestamp: data.timestamp  
    if (data.value == 2)
    {
      data.pic_url = data.pic_url + config.pic_rotate + "90"+ config.imgmark
    }
    else if (data.value == 3)
    {
      data.pic_url = data.pic_url + config.pic_rotate+"270" + config.imgmark
    }
    else
       data.pic_url = data.pic_url + config.imgmark
       
    console.log("pic_url:", data.pic_url )
    
    this.setData({
      info: data,
      uuid: uuid,
      phone: phone,
      unlocktimestamp: data.timestamp,
      value: data.value
    })

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  onShow() {
    var _this = this
    console.log("msg details onShow")

    this.setData({
      showMsgpopup: true
    })
  

    var unlockt_tmp = this.data.unlocktime
    // console.log("msg details1 unlockt", unlockt_tmp)
    if (unlockt_tmp > 1)
    {
      var hTime = this.data.msg_timestamp
      var qTime = parseInt(new Date().getTime() / 1000)

        if (qTime - hTime < 60) {
          var unlockt = hTime + 65 - qTime;
          // console.log("msg details2 unlockt", unlockt)

          _this.data.setInter = setInterval(function () {
          // console.log('unlockt', unlockt)
          if (unlockt > 1) {
            unlockt--;

            _this.setData({
              unlocktime: unlockt
            })
          }
          else {
            clearInterval(_this.data.setInter)
            _this.setData({
              unlockBtn: false
            })
          }

        }, 1000) //延迟时间 这里是1秒
      }

    }
    else
    {
      this.setData({
        unlockBtn: false,
      })
    }

   // app.AppGetDevList();
  },
  onHide() {
    console.log("msg details onHide")
    // if (this.data.setInter)
    clearInterval(this.data.setInter)

    this.setData({
      showMsgpopup: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("msg details onUnload")
    clearInterval(this.data.setInter)
    this.setData({
      showMsgpopup: false
    })
  },

  
})